<template>
  <div class="usermannge">
    <el-drawer
      v-model="isShow"
      :title="operateType === 'add' ? '新增用户' : '更新用户'"
    >
      <UserFrom
        :formLabel="opertateFormLabel"
        :operateType="operateType"
        :form="operateForm"
        ref="form"
        :inline="true"
      ></UserFrom>
      <div slot="footer" id="buttone" class="dialog-footer">
        <el-button class="userbtn" @click="isShow = false">取消</el-button>
        <el-button class="userbtn" type="primary" @click="confirm"
          >确定</el-button
        >
      </div>
    </el-drawer>

    <div class="manage-header">
      <el-button type="primary" @click="addUser">新增</el-button>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label-width="50px" label="详情">
          <el-input
            v-model="search"
            size="default"
            placeholder="请输入关键信息"
            @keypress.enter="filterTableData"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterTableData">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tablebox">
      <el-table
        :data="listdata.slice((page - 1) * limit, page * limit)"
        style="width: 100%"
      >
        <el-table-column fixed prop="id" label="用户id" width="70" />
        <el-table-column fixed prop="Account" label="账号" width="120" />
        <el-table-column prop="user_name" label="用户名" width="220" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="sex" label="性别">
          <template #default="scope">
            <el-tag
              class="mx-1"
              size="large"
              :type="scope.row.sex == 1 ? '' : scope.row.sex == 2?'success':'warning'"
            >
              {{ scope.row.sex == 1 ? "女" : scope.row.sex == 2 ? "男" :"保密"}}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="picture" label="City" width="320" /> -->
        <el-table-column prop="picture" label="缩略图" width="220">
          <template #default="scope">
            <el-popover placement="right" :width="100" title="" trigger="hover">
              <img
                :src="scope.row.picture"
                style="width: 125px; height: 120px"
              />
              <template #reference>
                <img
                  slots="reference"
                  :src="scope.row.picture"
                  style="width: 30px; height: 30px"
                />
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="created_At" label="注册时间" width="150" />
        <el-table-column prop="updated_At" label="更新时间" width="150" />
        <el-table-column prop="is_admin" label="用户身份" width="150">
          <template #default="scope">
            <el-tag
              class="mx-1"
              size="large"
              :type="
                scope.row.is_admin == 1
                  ? ''
                  : scope.row.is_admin == 2
                  ? 'success'
                  : scope.row.is_admin == 3
                  ? 'info'
                  : scope.row.is_admin == 4
                  ? 'warning'
                  : 'danger'
              "
            >
              {{
                scope.row.is_admin == 1
                  ? "管理员"
                  : scope.row.is_admin == 2
                  ? "党委"
                  : scope.row.is_admin == 3
                  ? "团支书"
                  : scope.row.is_admin == 4
                  ? "党员"
                  : "发展党员"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="用户编辑" width="150">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="large"
              @click="edituser(scope.$index, scope.row)"
            >
              <el-icon><Edit /></el-icon> 修改
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="deleteruser(scope.$index, scope.row)"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :currentPage="page"
        :page-size="limit"
        :page-sizes="[5, 10]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="TableDatatoal"
        @size-change="handleSizeChange"
        @current-change="CurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { getuserlist, adminuserupdate, registerApi,removeuser } from "@/request/user";
const list = reactive({
  listdata: [],
  operateType: "",
  isShow: false,
  editdata: [],
  limit: 5,
  page: 1,
  operateForm: {
    id: "",
    user_name: "",
    Account: "",
    email: "",
    picture: "",
    created_At: "",
    updated_At: "",
    is_admin: "",
    sex: "",
    age: "",
  },
  opertateFormLabel: [
    {
      model: "picture",
      label: "头像",
      type: "picture",
    },
    {
      model: "id",
      label: "用户id",
      type: "id",
    },
    {
      model: "user_name",
      label: "姓名",
      type: "input",
    },
    {
      model: "Account",
      label: "账号",
      type: "input",
    },
    {
      model: "email",
      label: "邮箱",
      type: "input",
    },
    {
      model: "age",
      label: "你暗恋",
      type: "num",
    },

    {
      model: "is_admin",
      label: "用户身份",
      type: "select",
      opts: [
        {
          label: "管理员",
          value: 1,
        },
        {
          label: "党委",
          value: 2,
        },
        {
          label: "团支书",
          value: 3,
        },
        {
          label: "党员",
          value: 4,
        },
        {
          label: "发展党员",
          value: 5,
        },
      ],
    },
    {
      model: "sex",
      label: "性别",
      type: "select",
      opts: [
        {
          label: "女",
          value: 1,
        },
        {
          label: "男",
          value: 2,
        },
        {
          label: "保密",
          value: 3,
        },
      ],
    },
    {
      model: "created_At",
      label: "注册时间",
      type: "date",
    },
    {
      model: "updated_At",
      label: "更新时间",
      type: "date",
    },
  ],
  active: {
    //选中的对象
    id: "",
    user_name: "",
    Account: "",
    email: "",
    picture: "",
    created_At: "",
    updated_At: "",
    is_admin: "",
    sex: "",
    age: "",
  },
});
let {
  listdata,
  operateType,
  isShow,
  editdata,
  operateForm,
  limit,
  page,
  opertateFormLabel,
  active,
} = toRefs(list);

const addUser = () => {
  //   console.log(list.opertateFormLabel);
  if (!list.opertateFormLabel.map((v) => v.model).includes("password")) {
    list.opertateFormLabel.push({
      model: "password",
      label: "密码",
      type: "input",
    });
  }
  list.isShow = true;
  list.operateType = "add";
  list.operateForm = {
    id: "",
    user_name: "",
    Account: "",
    email: "",
    picture: "",
    created_At: "",
    updated_At: "",
    sex: "",
    age: "",
    is_admin: "",
    password: "",
  };
};
const search = ref("");
onMounted(() => {
  getuserlistinfo();
});
watch([() => search.value], () => {
  if (search.value == "") {
    getuserlistinfo();
  }
});

const getuserlistinfo = async () => {
  let { userlist } = await getuserlist();
  for (let i = 0; i < userlist.length; i++) {
    userlist[i].created_At = userlist[i].created_At?.slice(0, 10);
    userlist[i].updated_At = userlist[i].updated_At?.slice(0, 10);
    userlist[i].picture = userlist[i].picture
      ? "/api/static/" + userlist[i].picture
      : "/api/static/default/default.png";
  }
  // console.log("userlist", userlist);
  // console.log("list.listdata ", list.listdata);
  //   console.log(userlist);
  list.listdata = userlist;
};

// 用户名搜索
let filterTableData = (val) => {
  // console.log(typeof search.value);
  let arr = [];
  if (search.value) {
    arr = list.listdata.filter((data) => {
      return data.user_name.indexOf(search.value.toString()) !== -1;
    });
  } else {
    arr = list.listdata;
  }
  // console.log(arr);
  list.listdata.length = arr.length;
  list.listdata = arr;
  // getuserlistinfo();
};

const confirm = async () => {
  let {
    id,
    Account,
    user_name,
    email,
    sex,
    age,
    is_admin,
    updated_At,
    created_At,
    password,
  } = list.operateForm;
  if (list.operateType === "edit") {
    // let data =list.operateForm;
    console.log("list.operateForm==========", list.operateForm);
    await adminuserupdate({
      id,
      Account,
      user_name,
      email,
      updated_At,
      created_At,
      is_admin,
      sex,
      age,
    }).then((res) => {
      console.log(res);
      let { code, message } = res;
      if (code === 200) {
        ElMessage({
          message: message,
          type: "success",
        });
      } else {
        ElMessage({
          message: message,
          type: "error",
        });
      }
    });
    list.isShow = false;
    getuserlistinfo();
    console.log("list.operateForm", list.operateForm);
  } else {
    registerApi({
      id,
      Account,
      user_name,
      email,
      sex,
      age,
      is_admin,
      updated_At,
      created_At,
      password,
    }).then((res) => {
      console.log(res);
      let { code, message } = res;
      if (code === 200) {
        ElMessage({
          message: "用户新增成功",
          type: "success",
        });
      } else {
        ElMessage({
          message: "用户新增失败" + "," + message,
          type: "error",
        });
      }
      getuserlistinfo();
      list.isShow = false;
    });
    console.log(list.operateForm);
  }
};

const edituser = (index, row) => {
  console.log(index, row);
  list.operateType = "edit";
  for (var i = 0; i < list.opertateFormLabel.length; i++) {
    if (list.opertateFormLabel[i].model.indexOf("password") > -1) {
      //判断key为999的对象是否存在，
      index = i;
      list.opertateFormLabel.splice(index, 1); //存在即删除
    }
  }
  // console.log("operateForm+++++++++++++++++", list.operateForm);

  list.editdata = row;
  list.operateForm = {
    id: row.id,
    user_name: row.user_name,
    Account: row.Account,
    email: row.email,
    picture: row.picture,
    created_At: row.created_At,
    updated_At: row.updated_At,
    is_admin: row.is_admin,
    sex: row.sex,
    age: row.age,
  };
  list.isShow = true;
};

// 分页
const TableDatatoal = computed(() => {
  // 该函数的返回值就是计算属性的值
  return list.listdata.length;
});

let handleSizeChange = (val) => {
  list.limit = val;
};
let CurrentChange = (val) => {
  list.page = val;
  // getuserlistinfo();
};

const deleteruser = (index, row) => {
  // removeuser()
  console.log(index, row);
  let {id} = row;
  removeuser({id}).then((res) => {
      console.log(res);
      let { code, result } = res;
      if (code === 200) {
        ElMessage({
          message: result,
          type: "success",
        });
      } else {
        ElMessage({
          message:result,
          type: "error",
        });
      }
      getuserlistinfo();
      // list.isShow = false;
    });
};
</script>

<style lang="scss" scoped>
.usermannge {
  width: 100%;
  height: 100%;
  :deep(.el-dialog) {
    // background-color: rgb(225, 161, 44);
    // max-width: 850px;
    // min-width: 300px;
    width: 50%;
  }
  .dialog-footer {
    // padding-left: 80%;
    width: 100%;
    height: 40px;
    // background-color: aqua;
    // letter-spacing: 40px;
    .userbtn {
      margin-left: 20px;
      float: right;
    }
  }

  .manage-header {
    width: 100%;
    height: 80px;
    display: flex;
    justify-content: space-between;
  }

  .userimg {
    width: 200px;
    height: 100px;
  }
  .tablebox {
    width: 100%;
  }
}
</style>
